package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description: 111. 二叉树的最小深度
 * User: Li_yizYa
 * Date: 2025/5/26
 * Time: 16:01
 */
public class Solution13 {
    /**
     * 非递归实现
     * @param root
     * @return
     */
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ret = 0;
        while (!queue.isEmpty()) {
            int len = queue.size();
            ret++;
            while (len > 0) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) {
                    return ret;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
        }
        return ret;
    }
    /**
     * 递归实现
     * @param root
     * @return
     */
    public int minDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int min = Integer.MAX_VALUE;
        if (root.left != null) {
            min = Math.min(minDepth1(root.left) + 1, min);
        }
        if (root.right != null) {
            min = Math.min(minDepth1(root.right) + 1, min);
        }
        return min;
    }
}
